package com.wondedDream.service.impl;

import com.wondedDream.constants.Constants;
import com.wondedDream.model.*;
import com.wondedDream.repository.*;
import com.wondedDream.service.MockExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class MockExamServiceImpl implements MockExamService {
    @Autowired
    private MockExamRepository mockExamRepository;
    @Autowired
    private MockExamQuestionRepository mockExamQuestionRepository;
    @Autowired
    private UserMockExamRecordRepository userMockExamRecordRepository;
    @Autowired
    private UserMockExamQuestionRecordRepository userMockExamQuestionRecordRepository;
    @Autowired
    private UserRepository userRepository;

    @Override
    public MockExam saveMockExam(MockExam exam) {
        return mockExamRepository.save(exam);
    }

    @Override
    public MockExam getMockExamById(Integer id) {
        return mockExamRepository.findById(id).orElse(null);
    }


    @Override
    public void deleteMockExam(Integer id) {
        mockExamRepository.deleteById(id);
    }

    @Override
    public MockExam updateMockExam(MockExam mockExam) {
        return mockExamRepository.saveAndFlush(mockExam);
    }

    // 实现统计方法，获取所有模考记录的统计信息
    @Override
    public List<UserMockExamRecord> getMockExamStatistics() {
        return userMockExamRecordRepository.findAll();
    }

    // 实现按时间范围统计模考记录的方法
    @Override
    public List<UserMockExamRecord> getMockExamStatisticsByTimeRange(String timeRange) {
        // 假设 timeRange 格式为 "yyyy-MM-dd HH:mm:ss - yyyy-MM-dd HH:mm:ss"
        String[] timeParts = timeRange.split(" - ");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTime = LocalDateTime.parse(timeParts[0], formatter);
        LocalDateTime endTime = LocalDateTime.parse(timeParts[1], formatter);

        return userMockExamRecordRepository.findBySubmitTimeBetween(startTime, endTime);
    }
    // 实现开始模考的方法
    @Override
    public void startMockExam(Integer userId, Integer mockExamId) {
        // 创建一个新的用户模考记录
        UserMockExamRecord record = new UserMockExamRecord();
        // 设置用户和模考对象，需要根据 userId 和 mockExamId 找到对应的 User 和 MockExam 对象
        User user = userRepository.findById(userId).orElse(null);
        MockExam mockExam = mockExamRepository.findById(mockExamId).orElse(null);
        record.setUser(user);
        record.setMockExam(mockExam);
        record.setStartTime(LocalDateTime.now());
        userMockExamRecordRepository.save(record);
    }

    // 实现记录模考答案的方法
    @Override
    public void recordMockExamAnswer(Integer mockExamId, String userOpenId) {
        UserMockExamRecord userMockExamRecord = userMockExamRecordRepository.findByUserIdAndMockExamId(userOpenId, mockExamId);
        if (userMockExamRecord != null) {
            userMockExamRecordRepository.delete(userMockExamRecord);
        }
        UserMockExamRecord newUserMockExamRecord = new UserMockExamRecord(new User(userOpenId), new MockExam(mockExamId), 0, 0l,
                null, LocalDateTime.now(), LocalDateTime.now());
        userMockExamRecordRepository.save(newUserMockExamRecord);
    }

    // 实现提交模考的方法
    @Override
    public void submitMockExam(UserMockExamRecord userMockExamRecord) {
        //获取用户答案
        Map<Integer, String> userAnswers = userMockExamRecord.getAnswers();
        //获取模考列表-原题答案
        List<MockExamQuestion> mockExamQuestions = mockExamQuestionRepository.findByMockExamId(userMockExamRecord.getMockExam().getId());
        //获取用户模考记录
        UserMockExamRecord lodUserMockExamRecord = userMockExamRecordRepository.findByUserIdAndMockExamId(userMockExamRecord.getUser().getOpenid(), userMockExamRecord.getMockExam().getId());
        List<UserMockExamQuestionRecord>  userMockExamQuestionRecords = new ArrayList<>();
        //计算得分
        int score = 0;
        for (MockExamQuestion question : mockExamQuestions) {
            Integer questionId = question.getId();
            String correctAnswer = question.getCorrectAnswer();
            if (userAnswers.containsKey(questionId)) {
                String userAnswer = userAnswers.get(questionId);
                if (userAnswer.equals(correctAnswer)) {
                    score++;
                    UserMockExamQuestionRecord userMockExamQuestionRecord = new UserMockExamQuestionRecord(userMockExamRecord.getMockExam(), userMockExamRecord.getUser(),
                            new MockExamQuestion(questionId), userAnswer, true, new Date());
                    userMockExamQuestionRecords.add(userMockExamQuestionRecord);
                }
            }
        }
        //更新模考记录表
        LocalDateTime nowTime = LocalDateTime.now();
        Duration duration = Duration.between(lodUserMockExamRecord.getStartTime(), nowTime);
        lodUserMockExamRecord.setDuration(duration.getSeconds());
        lodUserMockExamRecord.setSubmitTime(nowTime);
        lodUserMockExamRecord.setScore(score);
        userMockExamRecordRepository.saveAndFlush(lodUserMockExamRecord);
        //更新用户模考问题表
        userMockExamQuestionRecordRepository.deleteByUserIdAndMockExamId(userMockExamRecord.getUser().getOpenid(), userMockExamRecord.getMockExam().getId());
        userMockExamQuestionRecordRepository.saveAll(userMockExamQuestionRecords);
    }

    @Override
    public List<MockExam> getMockExamsByCategoryId(Integer categoryId) {
        return mockExamRepository.findByCategoryId(categoryId);
    }

    @Override
    public List<MockExam> getMockExamsByCategoryIdAndOpenId(Integer categoryId, String userOpenId) {
        //模考列表
        List<MockExam> mockExamList = mockExamRepository.findByCategoryId(categoryId);
        List<Integer> mockExamIdList = mockExamList.stream().map(MockExam::getId).collect(Collectors.toList());
        //模考记录，根据模考id判断是否参与过当前模考 参加列表改为已提交状态
        List<UserMockExamRecord> mockExamRecords = userMockExamRecordRepository.findByUserOpenIdAndMockExamId(userOpenId,mockExamIdList);
        if(mockExamRecords == null || mockExamRecords.size() == 0){
            mockExamList.forEach(mockExam -> {
                    mockExam.setSubmissionStatus(Constants.NOT_SUBMITTED_INT);
            });
            return mockExamList;
        }
        List<Integer> mockExamIds = mockExamRecords.stream()
                .map(UserMockExamRecord::getMockExam)
                .map(MockExam::getId)
                .collect(Collectors.toList());
        mockExamList.forEach(mockExam -> {
            if (mockExamIds.contains(mockExam.getId())) {
                mockExam.setSubmissionStatus(Constants.SUBMITTED_INT);
            }else{
                mockExam.setSubmissionStatus(Constants.NOT_SUBMITTED_INT);
            }
        });
        return mockExamList;
    }
}